import Vue from 'vue'
import VueRouter from 'vue-router'
const home = () => import('../components/home.vue')
const login = () => import('../views/login.vue')
const welcome = () => import('../components/welcome.vue')
const users = () => import('../components/user/user.vue')
const rights = () => import('../components/power/rights.vue')
const roles = () => import('../components/power/roles.vue')

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {path: '/', redirect: '/login'},
  {path: '/login', component: login},
  {
  path: '/home', 
  component: home,
  redirect: '/welcome',
  children: [
    {path: '/welcome',component: welcome},
    {path: '/users', component: users},
    {path: '/rights', component: rights},
    {path: '/roles', component: roles}
    //因为element-ui框架有自带的router，所以点击时URL会出现对应的地址，按照地址写进路由即可
  ]
  }
]



const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from, next) =>{
  /* 
  to:将要访问的路径
  from:代表从哪个路径跳转过来
  next:是一个函数，表示方行
  */
  if (to.path === '/login') return next()
  //根据前面sessionStorage存用户名和密码返回值判断,token是自己命名的键
  const token = window.sessionStorage('token')
  if (!token) return next('/login')
  next()
})

export default router
